package com.wisdytech.linkdcs.tool.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.enums.ToolRepairStatus;
import com.wisdytech.common.enums.ToolStatus;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.dao.*;
import com.wisdytech.linkdcs.tool.model.EqToolConfig;
import com.wisdytech.linkdcs.tool.model.ToolRepair;
import com.wisdytech.linkdcs.tool.model.ToolReplaceRecord;
import com.wisdytech.linkdcs.tool.model.TtEqTool;
import com.wisdytech.linkdcs.tool.service.IEqToolConfigService;
import com.wisdytech.linkdcs.tool.vo.ToolConfigVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-07
 */
@Service
@Transactional
public class EqToolConfigServiceImpl extends BaseService<EqToolConfigDao, EqToolConfig> implements IEqToolConfigService {

    @Resource
    private IEqEquipmentDao eqEquipmentDao;

    @Resource
    private ToolConfigDao toolConfigDao;

    @Resource
    private EqToolConfigDao eqToolConfigDao;

    @Resource
    private TtEqToolDao ttEqToolDao;

    @Resource
    private ToolReplaceRecordDao toolReplaceRecordDao;


    @Resource
    private ToolRepairDao toolRepairDao;

    @Override
    public List<Equipment> getEquipMentByEqCode(String equipCode) {
        EntityWrapper<Equipment> ew = new EntityWrapper<>();
        ew.eq("del_flag", CommonConstants.DEL_FLAG);
        if(StringUtils.isNotBlank(equipCode)) {
            ew.andNew().like("equip_code",equipCode).or().like("equip_name",equipCode);
        }
        return eqEquipmentDao.selectList(ew);
    }

    @Override
    public List<ToolConfigVO> getToolListByEquipCode(String equipCode) {
        List<ToolConfigVO> list = new ArrayList<>();
        if(StringUtils.isBlank(equipCode)) {
            return list;
        }
        list = toolConfigDao.getToolListByEquipCode(equipCode);
        return list;
    }

    @Override
    public PageInfo<EqToolConfig> getEqToolListByFilter(String equipCode, Filter filter) {
        if(StringUtils.isBlank(equipCode))
            return new PageInfo<>(new ArrayList<>());
        List<EqToolConfig> list = this.beforeList(EqToolConfigDao.class,filter).getEqToolListByFilter(equipCode);
        return new PageInfo<>(list);
    }

    @Override
    public Boolean saveEqToolConfig(EqToolConfig eqToolConfig, SysUser operator) {
        if(operator == null)
            throw new ServiceException("操作人不能为空");
        if(eqToolConfig == null||StringUtils.isBlank(eqToolConfig.getEquipCode())||StringUtils.isBlank(eqToolConfig.getToolCode())) {
            throw new ServiceException("参数错误");
        }
        //校验工装状态
        if (!checkToolStatus(eqToolConfig.getToolCode()))
            throw new ServiceException("工装状态不可用");
        //check equip position
        EntityWrapper<EqToolConfig> ew = new EntityWrapper<>();
        ew.eq("equip_code",eqToolConfig.getEquipCode())
                .eq("equip_position",eqToolConfig.getEquipPosition());
        if (eqToolConfigDao.selectCount(ew)>0) {
            throw new ServiceException("设备位置重复");
        }

        eqToolConfig.setCreateDate(new Date());
        eqToolConfig.setCreateUser(operator.getUsername());
        eqToolConfig.setDelFlag(CommonConstants.DEL_FLAG);
        eqToolConfig.setPkId(BaseUtil.getUUID());
        Integer count = eqToolConfigDao.insert(eqToolConfig);
        //更新新工装状态为使用中
        TtEqTool tool = new TtEqTool();
        tool.setStatus("2");
        tool.setToolCode(eqToolConfig.getToolCode());
        if(count >0)
            ttEqToolDao.updateToolStatusByToolCode(tool);
        return count>0;
    }

    /**
     *
     * 工装更换流程
     * 1.检查新换上的工装是否可用
     * 2.检测原工装是否维修或者报废
     *  2.1维修在维修表中插入记录
     *  2.2报废直接修改工装状态为报废
     *  2.3既不报废也不维修 更新原工装状态为可使用
     * 3.插入工装更换记录
     *  3.1捷威项目新增了使用时间和产量，需要在更换时计算原工装的使用时间
     *
     *
     * @param eqToolConfig 实体类
     * @param operator 操作人
     * @return 操作结果
     */
    @Override
    public Boolean replaceTool(EqToolConfig eqToolConfig, SysUser operator) {
        //java 8 Optional lambda语法
        Optional.ofNullable(operator)
                .orElseThrow(()->new ServiceException("操作人不能为空"));
        Optional.ofNullable(eqToolConfig)
                .filter(x->StringUtils.isNotBlank(x.getPkId()))
                .filter(x->StringUtils.isNotBlank(x.getToolCode()))
                .filter(x->StringUtils.isNotBlank(x.getOriginToolCode()))
                .orElseThrow(()->new ServiceException("参数错误"));
        //校验工装状态
        if (!checkToolStatus(eqToolConfig.getToolCode()))
            throw new ServiceException("工装状态不可用");
        //维修
        if ("1".equals(eqToolConfig.getRepair())) {
            //插入维修表中
            ToolRepair repair = new ToolRepair();
            repair.setEquipCode(eqToolConfig.getEquipCode());
            repair.setPkId(BaseUtil.getUUID());
            repair.setDelFlag(CommonConstants.DEL_FLAG);
            repair.setCreateDate(new Date());
            repair.setCreateUser(operator.getUsername());
            //插入tool_code 为 更换下来的
            repair.setToolCode(eqToolConfig.getOriginToolCode());
            toolRepairDao.insert(repair);
            //更新工装状态为不可用和维修状态为待维修
            TtEqTool tool = new TtEqTool();
            tool.setToolCode(eqToolConfig.getOriginToolCode());
            tool.setStatus(ToolStatus.UNAVAILABLE.getCode());
            tool.setRepairStatus(ToolRepairStatus.NEED_REPAIR.getCode());
            ttEqToolDao.updateStatusByToolCode(tool);
        }
        //报废 更新工装状态为不可用和维修状态为报废
        if ("1".equals(eqToolConfig.getScrap())) {
            TtEqTool tool = new TtEqTool();
            tool.setToolCode(eqToolConfig.getOriginToolCode());
            tool.setRepairStatus(ToolRepairStatus.SCRAPED.getCode());
            tool.setStatus(ToolStatus.UNAVAILABLE.getCode());
            ttEqToolDao.updateRepairStatusByToolCode(tool);
        }
        //既不报废，也不送修
        if((!("1".equals(eqToolConfig.getRepair())))&&(!("1".equals(eqToolConfig.getScrap())))) {
            TtEqTool tool = new TtEqTool();
            tool.setToolCode(eqToolConfig.getOriginToolCode());
            //tool.setRepairStatus(ToolRepairStatus.SCRAPED.getCode());
            tool.setStatus(ToolStatus.USABLE.getCode());
            ttEqToolDao.updateToolStatusByToolCode(tool);
        }

        //记录上次更换时间
        EqToolConfig var1 = eqToolConfigDao.selectById(eqToolConfig.getPkId());
        if (var1 == null) {
            throw new ServiceException("数据异常，无法查询到该条工装和设备记录");
        }
        //取上次更换日期或者创建日期
        Date lastReplaceDate = var1.getReplaceDate() == null?var1.getCreateDate():var1.getReplaceDate();
        Date nowReplaceDate = eqToolConfig.getReplaceDate();
        //计算工作天数
        long lifeCycleLong =  (nowReplaceDate.getTime()-lastReplaceDate.getTime())/(1000*3600*24);
        int lifeCycle = (int)lifeCycleLong;

        eqToolConfig.setUpdateDate(new Date());
        eqToolConfig.setUpdateUser(operator.getUsername());
        Integer count = eqToolConfigDao.updateById(eqToolConfig);
        //更新新工装状态为使用中
        TtEqTool tool = new TtEqTool();
        tool.setStatus(ToolStatus.USING.getCode());
        tool.setToolCode(eqToolConfig.getToolCode());
        if(count >0)
        ttEqToolDao.updateToolStatusByToolCode(tool);

        //新增更换记录
        ToolReplaceRecord record = new ToolReplaceRecord();
        record.setPkId(BaseUtil.getUUID());
        record.setCreateDate(new Date());
        record.setCreateUser(operator.getUsername());
        record.setDelFlag(CommonConstants.DEL_FLAG);
        record.setEquipCode(eqToolConfig.getEquipCode());
        record.setOriginToolCode(eqToolConfig.getOriginToolCode());
        record.setReplaceToolCode(eqToolConfig.getToolCode());
        record.setReplaceDate(eqToolConfig.getReplaceDate());
        record.setReplaceUser(eqToolConfig.getReplaceUser());
        record.setReplaceReason(eqToolConfig.getReplaceReason());
        record.setRemark(eqToolConfig.getRemark());
//        EqToolConfig eqTool = new EqToolConfig();
//        eqTool.setEquipCode(eqToolConfig.getEquipCode());
//        eqTool.setToolCode(eqToolConfig.getToolCode());
//        eqTool.setDelFlag(CommonConstants.DEL_FLAG);
        EqToolConfig eqTool = eqToolConfigDao.selectById(eqToolConfig.getPkId());
        if(eqTool!=null){
            record.setEquipPosition(eqTool.getEquipPosition());
        }
        //捷威新增字段(产量和使用时间)
        record.setQuantity(eqToolConfig.getQuantity());
        record.setLifeCycle(lifeCycle);
        toolReplaceRecordDao.insert(record);
        return count > 0;
    }

    @Override
    public Boolean checkToolStatus(String toolCode) {
        if (StringUtils.isBlank(toolCode))
            return false;
        //校验工装状态
        TtEqTool params = new TtEqTool();
        params.setDelFlag(CommonConstants.DEL_FLAG);
        params.setToolCode(toolCode);
        TtEqTool tool = this.ttEqToolDao.selectOne(params);
        if(tool == null) {
            return false;
        }
        if(!ToolStatus.USABLE.getCode().equals(tool.getStatus())) {
            return false;
        }

        //校验工装是否已经被使用(可以注释掉下面的代码，因为工装状态为可用，应该就不会被其他设备使用)
        EntityWrapper<EqToolConfig> ew = new EntityWrapper<>();
        ew.eq("del_flag",CommonConstants.DEL_FLAG)
                .eq("tool_code",toolCode);
        Integer count = eqToolConfigDao.selectCount(ew);
        return count <= 0;
    }

	@Override
	public List<EqToolConfig> getToolConfigByToolCode(String equipCode, Filter filter, String toolCode) {
        if(StringUtils.isBlank(equipCode))
            return new ArrayList<>();
        List<EqToolConfig> list = this.beforeList(EqToolConfigDao.class,filter).getToolConfigByToolCode(equipCode,toolCode);
        return list;
	}

	@Override
	public List<ToolConfigVO> getToolListBytoolCode(String equipCode, String toolCode) {
        List<ToolConfigVO> list = new ArrayList<>();
        if(StringUtils.isBlank(equipCode)) {
            return list;
        }
        list = toolConfigDao.getToolListBytoolCode(equipCode,toolCode);
        return list;
	}
	
	
	
    @Override
    public void replaceToolTemp(EqToolConfig eqToolConfig, SysUser operator,String equipId) {
        if(operator == null)
            throw new ServiceException("操作人不能为空");
        if(eqToolConfig == null||StringUtils.isBlank(eqToolConfig.getToolCode())||StringUtils.isBlank(eqToolConfig.getOriginToolCode())) {
            throw new ServiceException("参数错误");
        }
        //校验工装状态
        if (!checkToolStatus(eqToolConfig.getToolCode()))
            throw new ServiceException("工装状态不可用");
        //维修
        if ("1".equals(eqToolConfig.getRepair())) {
            //插入维修表中
            ToolRepair repair = new ToolRepair();
			repair.setEquipCode(eqToolConfig.getEquipCode());
            repair.setPkId(BaseUtil.getUUID());
            repair.setDelFlag(CommonConstants.DEL_FLAG);
            repair.setCreateDate(new Date());
            repair.setCreateUser(operator.getUsername());
            //插入tool_code 为 更换下来的
            repair.setToolCode(eqToolConfig.getOriginToolCode());
            toolRepairDao.insert(repair);
            //更新工装状态为不可用和维修状态为待维修
            TtEqTool tool = new TtEqTool();
            tool.setToolCode(eqToolConfig.getOriginToolCode());
            tool.setStatus(ToolStatus.UNAVAILABLE.getCode());
            tool.setRepairStatus(ToolRepairStatus.NEED_REPAIR.getCode());
            ttEqToolDao.updateStatusByToolCode(tool);
        }
        //报废 更新工装状态为不可用和维修状态为报废
        if ("1".equals(eqToolConfig.getScrap())) {
            TtEqTool tool = new TtEqTool();
            tool.setToolCode(eqToolConfig.getOriginToolCode());
            tool.setRepairStatus(ToolRepairStatus.SCRAPED.getCode());
            tool.setStatus(ToolStatus.UNAVAILABLE.getCode());
            ttEqToolDao.updateRepairStatusByToolCode(tool);
        }
		//既不报废，也不送修
        if((!("1".equals(eqToolConfig.getRepair())))&&(!("1".equals(eqToolConfig.getScrap())))) {
            TtEqTool tool = new TtEqTool();
            tool.setToolCode(eqToolConfig.getOriginToolCode());
            //tool.setRepairStatus(ToolRepairStatus.SCRAPED.getCode());
            tool.setStatus(ToolStatus.USABLE.getCode());
            ttEqToolDao.updateToolStatusByToolCode(tool);
        }

        eqToolConfig.setUpdateDate(new Date());
        eqToolConfig.setUpdateUser(operator.getUsername());
        EntityWrapper<EqToolConfig> ew = new EntityWrapper();
        ew.eq("EQUIP_CODE",eqToolConfig.getEquipCode());
        ew.eq("TOOL_CODE",eqToolConfig.getOriginToolCode());
        ew.eq("DEL_FLAG",CommonConstants.DEL_FLAG);
		
		
        Integer count = eqToolConfigDao.update(eqToolConfig,ew);
//        Integer count = eqToolConfigDao.updateById(eqToolConfig);
        //更新新工装状态为使用中
        TtEqTool tool = new TtEqTool();
        tool.setStatus(ToolStatus.USING.getCode());
        tool.setToolCode(eqToolConfig.getToolCode());
        if(count >0)
        ttEqToolDao.updateToolStatusByToolCode(tool);

        //新增更换记录
        ToolReplaceRecord record = new ToolReplaceRecord();
        record.setPkId(BaseUtil.getUUID());
        record.setCreateDate(new Date());
        record.setCreateUser(operator.getUsername());
        record.setDelFlag(CommonConstants.DEL_FLAG);
        //查询equipCode
        Equipment equipment = eqEquipmentDao.selectById(equipId);
        record.setEquipCode(equipment.getEquipCode());
        record.setOriginToolCode(eqToolConfig.getOriginToolCode());
        record.setReplaceToolCode(eqToolConfig.getToolCode());
        record.setReplaceDate(eqToolConfig.getReplaceDate());
        record.setReplaceUser(eqToolConfig.getReplaceUser());
        record.setReplaceReason(eqToolConfig.getReplaceReason());
        record.setRemark(eqToolConfig.getRemark());
        record.setEquipPosition(eqToolConfig.getEquipPosition());
        toolReplaceRecordDao.insert(record);
    }

    @Override
    public List<CollectionParam> findCollectionParamByEquipCode(String equipCode, String search) {
        if (StringUtils.isBlank(equipCode)) {
            return null;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("equipCode",equipCode);
        if (StringUtils.isNotBlank(search)) {
            params.put("equipParam",search);
        }
        return this.toolRepairDao.selectCollectionParamByEquipCode(params);
    }

    @Override
    public EqToolConfig getoToolBytoolCode(String equipCode, String toolCode) {
        return eqToolConfigDao.getoToolBytoolCode(equipCode,toolCode);
    }
}
